package com.tude._07vehicle.base.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalTime;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class RateLimitInterceptor implements HandlerInterceptor {
    private static final int MAX_REQUESTS_PER_MINUTE = 3;
    private static final int WINDOW_SIZE_SECONDS = 60;
    private static final ConcurrentHashMap<String, Integer> requestCounts = new ConcurrentHashMap<>();
    private static final ConcurrentHashMap<String, LocalTime> lastRequestTimes = new ConcurrentHashMap<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("进入访问限流拦截器...");
        // 获取客户端IP
        String attr = request.getRemoteAddr();
        // 获取并判断时间
        LocalTime lastTime = lastRequestTimes.get(attr);
        if(lastTime == null || lastTime.isAfter(LocalTime.now().plusSeconds(WINDOW_SIZE_SECONDS))) {
            // 计数器清零
            requestCounts.put(attr, 0);
            // 记录访问时间
            lastRequestTimes.put(attr, LocalTime.now());
        }
        //计数器+1
        int i = requestCounts.merge(attr, 1, Integer::sum);

        if (i > MAX_REQUESTS_PER_MINUTE) {
            throw new RuntimeException("请求过于频繁，请稍后再试");
        }
        return true;
    }
}
